/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:46:27
 * @LastEditTime: 2021-12-24 11:36:19
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \godriver\opdb\example\write\write.go
 * hnxr
 */
package main

import (
	"log"
	"os"
	"strings"
	"time"

	"gitee.com/haodreams/godriver/opdb"
	"gitee.com/haodreams/godriver/opdb/opsql"
	"gitee.com/haodreams/golib/env"
	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/libs/ee"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

func main() {
	env.Reset()
	data, err := os.ReadFile("conf.txt")
	if err != nil {
		log.Fatalln(err)
	}

	ss := strings.Split(string(data), ";")
	dataSource := strings.TrimSpace(ss[0])

	dialector := opsql.Open(dataSource)
	if dialector == nil {
		ee.NewError("不支持的驱动:" + dataSource).Once2(logs.CbErrorf)
		return
	}
	op, err := gorm.Open(dialector, &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	if err != nil {
		log.Fatalln(err)
	}
	//查询服务器时间
	tm := ""
	err = op.Raw("SELECT time").First(&tm).Error
	if err != nil {
		log.Fatalln(err)
	}
	log.Println("服务器时间:", tm)

	if len(ss) < 2 {
		log.Fatalln("没有需要发送的数据")
	}

	var reals []*opdb.Real
	var rows []interface{}

	ss = strings.Split(ss[1], ",")
	for i := range ss {
		real := new(opdb.Real)
		real.Name = ss[i]
		reals = append(reals, real)
		rows = append(rows, real)
	}

	//发送1000次
	for i := 0; i < 1000; i++ {
		t := time.Now().Unix()
		for j := 0; j < len(reals); j++ {
			reals[j].Value = float64(t % 60)
		}

		db, err := op.DB()
		if err != nil {
			logs.Error(err)
			return
		}
		_, err = db.Exec("Write Realtime", rows...)

		if err != nil {
			logs.Error(err)
			return
		}
		time.Sleep(time.Second)
	}
}
